<?php
namespace app\service\http\google\maps;

use app\service\http\google\GoogleApiClient;
use hunma\exception\ApiException;

class HttpGoogleMaps extends GoogleApiClient
{
    public function geocode($address, array $options = [])
    {
        $geocodeData = parent::get('maps/api/geocode/json', [
            'address' => $address,
        ], [], $options);

        if (isset($geocodeData['error_message'])) {
            throw new ApiException('Google Maps Geocoding API error: ' . $geocodeData['error_message']);
        }

        // 检查状态是否成功
        if ($geocodeData['status'] !== 'OK') {
            throw new ApiException('Geocoding failed: ' . ($geocodeData['error_message'] ?? $geocodeData['status']));
        }

        // 检查是否有结果
        if (empty($geocodeData['results'])) {
            return null;
        }

        // 获取第一个结果中的坐标
        if (isset($geocodeData['results'][0]['geometry']['location'])) {
            $location = $geocodeData['results'][0]['geometry']['location'];
            return [
                'lat' => $location['lat'],
                'lng' => $location['lng']
            ];
        }

        return null;
    }
}